/* easy validate form field active scrubbing */
$(document).ready(function(){
	Validate.init();
});
Validate = {
	init:function(){
		//get keyup elements and focusout elements
		var $keyups = $('input[validate],textarea[validate]');
		var $focusOuts = $('input[validate],textarea[validate],select[validate]');
		
		//attach handlers to each
		$keyups.each(function(){
			var $this = $(this);
			var words = $this.attr('validate');
			
			// attach handler
			$this.on('keyup',function(){
				Validate.inputKeyup($(this));
			});
			
			// swap validate attribute
			$this.removeAttr('validate');
			$this.attr('validate_on',words);
		});
		$focusOuts.each(function(){
			var $this = $(this);
			var words = $this.attr('validate');
			
			// attach handler
			$this.on('blur',function(){
				// wait just a split fucking second
				var $this = $(this);
				setTimeout(function(){
					Validate.inputFocusout($this);
				},100);
			});
			
			// swap validate attribute
			$this.removeAttr('validate');
			$this.attr('validate_on',words);
		});
		
		//hijack forms submit
		$('form').not('[validate_on]').each(function(){
			var $form = $(this);
			$form.submit(function(event){
				if(!Valid.check($(this))){
					event.preventDefault();
				}
			});
			$form.attr('validate_on','');
		});
		// then finish email focusout
	},
	inputKeyup:function(jInput){
		var words = Validate.getWords(jInput);
		var inputString = jInput.val();
		if(words.match(/number/i)){
			inputString = Vw.number(inputString);
			if(words.match(/positive/i)){
				inputString = Vw.positive(inputString);
			}
			if(words.match(/maximum/i)) {
				inputString = Vw.maximum(inputString,words);
			}
			if(words.match(/integer/i) && !words.match(/money/i)){
				inputString = Vw.integer(inputString);
			}
			if(words.match(/maxlength/i)){
				inputString = Vw.maxlength(inputString,words);
			}
		} else {
			if(words.match(/maxlength/i)){
				inputString = Vw.maxlength(inputString,words);
			}
			if(words.match(/nospace/i)){
				inputString = Vw.noSpace(inputString);
			}
			if(words.match(/nocomma/i)){
				inputString = Vw.noComma(inputString);
			}
		}
		if(jInput.val() != inputString){ // only overwrite page if inputString has been changed.
			Validate.setInputAndCursor(inputString,jInput.get(0));
		}
	},
	
	inputFocusout:function(jInput){
		var issues = "";
		var words = Validate.getWords(jInput);
		var inputString = jInput.val() || "";
		if(words.match(/number/i)){
			inputString = Vw.numberFocusout(inputString,words);
			if(words.match(/money/i)){
				inputString = Vw.moneyFocusout(inputString);
			}
		}
		// mininimLength
		if(words.match(/minLength/i)){
			var min = Vw.getWordValue(words,'minLength');
			if(inputString.length < min && inputString.length != 0){
				issues = $h.listAppend(issues,'at least '+min+' chars');
			}
		}
		
		// email
		if(words.match(/email/i) && !Valid.email(inputString)){
			issues = $h.listAppend(issues,'check email');
		}

		// required
		if(words.match(/required/i)){
			if(inputString == ""){
				issues = $h.listAppend(issues,'required');
			}
		}
		if(issues != ""){
			Validate.addIssue(jInput,issues);
		} else {
			Validate.removeIssue(jInput);
		}
		jInput.val(inputString);
	},
	
	setInputAndCursor: function(inputString,thisElement) { // relocates the cursor so typing flows naturally for keyup's
		var position = 0;
		if (document.selection) {
			thisElement.focus();
			var Sel = document.selection.createRange ();
			Sel.moveStart ('character', -thisElement.value.length);
			position = Sel.text.length;
		} else if (thisElement.selectionStart || thisElement.selectionStart == '0'){
			position = thisElement.selectionStart;
		}
		var offset = inputString.length - $(thisElement).val().length;
		$(thisElement).val(inputString);
		try{
			thisElement.setSelectionRange(position+offset,position+offset);
		}catch(e){
			// do nothing.  sometimes this fails because the element is no longer focused.
		}
	},
	
	getWords:function(jInput){
		var wordList = jInput.attr('validate_on') || "";
		// remove the float property that sneaks in to this list for whatever reason.
		wordList = wordList.replace("float","");
		wordList = wordList.toLowerCase();
		// if a number word, number filter is prerequisite
		if(wordList.indexOf('number') == -1 && (wordList.indexOf('integer') > -1 || wordList.indexOf('positive') > -1 || wordList.indexOf('money') > -1 || wordList.indexOf('maximum') > -1 || wordList.indexOf('minimum') > -1 || wordList.indexOf('money') > -1)){
			wordList = 'number,' + wordList;
		}
		return wordList;
	},
	
	getWordNumber: function(words,word) {
		var number = "";
		var location = words.toLowerCase().indexOf(word.toLowerCase());
		for(var i = location+word.length; i < words.length; i++){
			if(isNaN(words.charAt(i)) && words.charAt(i) != "."){
				break;
			} else {
				number += words.charAt(i);
			}
		}
		return number;
	},
	check: function(jArea){
		// check required
		var result = true;
		jArea.find('input[validate],select[validate]').each(function(){
			var jThis = $(this);
			var value = jThis.val() || "";
			var words = Validate.getWords(jThis);
			if(words.toLowerCase().indexOf('required') > 0 && value == ""){
				jThis.addClass('validation_failed');
				var result = false;
			}
		});
		return false;
	},
	addValidation:function($input,word){
		var currentWords = Validate.getWords($input).toLowerCase();
		var word = word.toLowerCase();
		currentWords = currentWords.replace(word+',',"");
		currentWords = currentWords.replace(word,"");
		if(currentWords.length > 0 && currentWords.charAt(currentWords.length-1) != ","){
			currentWords += ",";
		}
		$input.attr('validate_on',currentWords+word);
	},
	removeValidation:function($input,word){
		var currentWords = Validate.getWords($input).toLowerCase();
		var word = word.toLowerCase();
		currentWords = currentWords.replace(word+',',"");
		currentWords = currentWords.replace(word,"");
		if(currentWords.charAt(currentWords.length-1) == ','){
			currentWords = currentWords.substring(0,currentWords.length-1);
		}
		$input.attr('validate_on',currentWords);
	},
	addIssue:function($input,text){
		var name = $input.attr('name');
		// find and remove existing issue
		var $oldSpan = $('span.validation_issue[name='+name+']');
		if($oldSpan.length > 0){
			$oldSpan.remove();
		}
		// change letter spacing based on length
		var letterSpacing = "1px";
		if(text.length > 14){
			letterSpacing = "0px";
		}
		// create and define span
		var $span = $('<span class="validation_issue" name="'+name+'">'+text+'</span>');
		$span.css({
			"position":"absolute",
			"color":"red",
			"fontSize":"10px",
			"marginTop":"-2px",
			"marginLeft":"7px",
			"display":"none",
			"letterSpacing":letterSpacing,
			"textShadow":"0px 0px 4px white",
			"padding":"0px 2px",
			"background-color":"white",
			"borderRadius":"5px"
		});
		$span.on('click',function(){
			var $form = $(this).closest('form');
			$form.find('input[name='+$(this).attr('name')+']').focus();
		});
		$input.before($span);
		$span.fadeIn(250,function(){
			setTimeout(function(){
				$span.fadeOut(250,function(){
					$span.remove();
				});
			},1500);
		});
	},
	removeIssue:function($input){
		var $form = $input.closest('form');
		var name = $input.attr('name');
		// find and remove existing issue
		var $oldSpan = $form.find('span.validation_issue[name='+name+']');
		if($oldSpan.length > 0){
			$oldSpan.fadeOut(250,function(){
				$oldSpan.remove();
			});
		}
	}
};